package com.cjf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjf.comon.R;
import com.cjf.entity.User;
import com.cjf.service.UserService;
import com.cjf.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.util.Map;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /***
     * 发送随机验证码
     * @param user
     * @param httpSession
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession) {
        //获取手机号
        String phone = user.getPhone();

        //手机号不为空
        if (StringUtils.isNotEmpty(phone)) {
            //生成随机4位的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("验证码：{}", code);

            //将手机号、生成的验证码保存到Session中
            httpSession.setAttribute("phone", phone);
            httpSession.setAttribute("code", code);

            return R.success("验证码发送成功！");
        }
        return R.error("验证码发送失败！");
    }

    /***
     * 移动端用户登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession httpSession) {

        log.info(map.toString());

        //获取用户输入的手机号
        String phone = map.get("phone").toString();
        //获取用户输入的验证码
        String code = map.get("code").toString();
        //从Session中获取后台生成的验证码
        Object code1 = httpSession.getAttribute("code");

        System.out.println("session验证码=" + code1);

        //进行验证码校验
        if (code1 != null && code.equals(code1)) {

            log.info("验证成功");
            //条件构造器
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);

            //user不存在 进行注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            //登录成功
            httpSession.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登录失败!");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession httpSession) {
        httpSession.invalidate();
        return R.success("退出成功！");
    }
}
